<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { getPalyFileApi } from '@/api/table'
import { GetCheckDetailsApi, EditCheckResultApi } from '@/api/assessment'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import DPlayer from 'dplayer'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const { push, go } = useRouter()
const route = useRoute()
const { t } = useI18n()
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
console.log('-------', route.query, route.params)
const searchParams = ref({})
if (route.query) {
  searchParams.value = route.query
}
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'assessmentType',
    label: '抽查类型'
  },
  {
    field: 'assessmentCount',
    label: '抽查数量'
  },
  {
    field: 'depName',
    label: t('userDemo.department')
  },
  {
    field: 'score',
    label: '评分'
  },
  {
    field: 'detailContent',
    label: '评价内容'
  },
  {
    field: 'remark',
    label: '备注'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 100,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => look(data.row)}>
              修改
            </BaseButton>
          </>
        )
      }
    }
  }
]

const showDetail = ref(false)
let saveLoading = ref(false)
const showVideoLoading = ref(false)
const currentRow = ref()
let videoUrl = ref()
const videoRef = ref()
const look = async (row) => {
  showDetail.value = true
  showVideoLoading.value = true
  currentRow.value = row
  setValues(row)
  getPalyFileApi({ fileGuid: row.fileGuid })
    .then((res) => {
      videoUrl.value = res.data
      // const videoFile = new Blob([res.data], {
      //   type: 'video/mp4'
      // })
      // videoUrl.value = URL.createObjectURL(videoFile)
      // console.log('videoUrl.value---', unref(videoUrl.value))
      // const dp = new DPlayer({
      //   container: videoRef.value,
      //   autoplay: true,
      //   theme: '#FADFA3',
      //   loop: true,
      //   lang: 'zh-cn',
      //   screenshot: true,
      //   hotkey: true,
      //   preload: 'auto',
      //   // logo: 'logo.png',
      //   volume: 0.7,
      //   mutex: true,
      //   video: {
      //     url: videoUrl.value,
      //     type: 'flv'
      //   }
      // })

      showVideoLoading.value = false
    })
    .catch(() => {
      showVideoLoading.value = false
      ElMessage({
        message: '视频加载失败',
        type: 'error'
      })
    })
}

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData) {
      saveLoading.value = true
      let res = await EditCheckResultApi({ ...unref(currentRow), ...formData }).finally(() => {
        saveLoading.value = false
      })

      if (res) {
        getList()
        showDetail.value = false
      }
    }
  }
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    // const { pageSize, currentPage } = tableState
    const res = await GetCheckDetailsApi({
      ...unref(searchParams)
    })
    return {
      list: res.data || [],
      total: res.data.length || 0
    }
  }
  //   fetchDelApi: async () => {
  //     const res = await deleteFiles(unref(ids))
  //     return !!res
  //   }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const formSchema = ref<FormSchema[]>([
  {
    field: 'score',
    label: '评分',
    component: 'Input',
    componentProps: {
      placeholder: '请输入',
      type: 'number'
    }
  },
  {
    field: 'detailContent',
    label: '评价内容',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '180px' }
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '120px' }
    }
  }
])

const rules = reactive({
  score: [required()],
  detailContent: [required()]
})
const videoError = (e) => {
  console.log('videoError---', e)
  ElMessage({
    message: '视频加载失败',
    type: 'error'
  })
}
</script>

<template>
  <ContentDetailWrap>
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
    </template>
    <!-- <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" /> -->
    <Table
      :reserveIndex="true"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
    <!--  :video-preview="['filePath']" -->
    <Dialog v-model="showDetail" title="详情">
      <div class="row_d">
        <video
          :src="videoUrl"
          ref="videoRef"
          controls
          style="width: 400px; height: 400px; background: #000"
          preload="auto"
          autoplay
          v-loading="showVideoLoading"
          @error="videoError"
        ></video>
        <!-- <div ref="videoRef" style="width: 400px; height: 400px" v-loading="showVideoLoading"></div> -->
        <div class="rombox">
          <Form :rules="rules" @register="formRegister" :schema="formSchema" :isCol="false" />
        </div>
      </div>
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="showDetail = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentDetailWrap>
</template>
<style scoped>
::v-deep .dplayer-menu,
.dplayer-mask {
  display: none !important;
}
.row_d {
  display: flex;
  /* align-items: center; */
}
.rombox {
  width: 500px;
  margin-left: 20px;
}
.downstyle {
  margin-right: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 500;
  -webkit-user-select: none;
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: #529b2e;
  border: var(--el-border);
  border-color: #529b2e;
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  text-decoration: none;
}
</style>
